<template>
  <div>
    <!-- 页面头部 -->
    <div class="page-header flex align-center space-between">
      <div class="font-weight--lg font-size--lg">
        <span v-show="currentNode">{{ currentNode ? currentNode.name : '' }}</span>
        <span>（{{ pageCount }}人）</span>
      </div>
    </div>
    <!-- 页面内容 -->
    <div class="page-body">
      <el-form :model="queryForm" :inline="true" ref="queryFormRef" size="small" @submit.native.prevent>
        <el-form-item>
          <el-input size="small" placeholder="请输入账号/姓名/手机号" v-model.trim="queryForm.search" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-select size="small" placeholder="请选择账号状态" v-model="queryForm.status">
            <el-option v-for="item in statusDataList" :key="'status' + item.value" :label="item.label" :value="item.value"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="small" class="width_104" type="primary" @click="getPageDataList()">查询</el-button>
          <el-button size="small" class="width_104" @click="resetOption()">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button size="mini" type="success" icon="el-icon-document-add" @click="addMemberOption()" v-if="roleBtns.includes('sys:user:add') || $store.getters.isAdmin" :disabled="currentNode && !currentNode.isEnable">添加成员</el-button>
        <el-button size="mini" type="warning" icon="el-icon-refresh" @click="memberChangeOption()" v-if="roleBtns.includes('sys:user:updatedep') || $store.getters.isAdmin" :disabled="currentNode && !currentNode.isEnable">调整部门</el-button>
        <el-button size="mini" type="danger" icon="el-icon-delete" @click="memberRemoveOption()" v-if="roleBtns.includes('sys:user:remove') || $store.getters.isAdmin">批量删除</el-button>
      </div>
      <el-table class="margin_top_20" stripe :data="pageData" :header-cell-style="tableHeaderStyle" row-key="id" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="42"></el-table-column>
        <el-table-column prop="username" label="账号"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="roleName" label="权限组">
          <template slot-scope="scope">
            <div class="text-ellipsis_2" :title="scope.row.roleName">{{scope.row.roleName}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column prop="checkStatus" label="是否启用">
          <template slot-scope="scope">
            <el-switch @change="changeStatus($event, scope.row)" :value="scope.row.checkStatus == 0"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template slot-scope="scope">
            <button class="my-btn my-btn--mini my-btn--primary plain" @click="configOption(scope.row)" v-if="roleBtns.includes('sys:user:config') || $store.getters.isAdmin" :disabled="(currentNode && !currentNode.isEnable) || scope.row.checkStatus != 0">分配权限</button>
            <button class="my-btn my-btn--mini my-btn--primary plain" @click="editMemberOption(scope.row)" v-if="roleBtns.includes('sys:user:update') || $store.getters.isAdmin" :disabled="(currentNode && !currentNode.isEnable) || scope.row.checkStatus != 0">编辑</button>
            <button class="my-btn my-btn--mini my-btn--danger plain" @click="removeDepartChildOption([scope.row.id])" v-if="roleBtns.includes('sys:user:remove') || $store.getters.isAdmin">删除</button>
          </template>
        </el-table-column>
      </el-table>
      <div class="text-center">
        <br>
        <el-pagination background @size-change="handleSizeChange" @current-change="handlePagingChange" :current-page="pageIndex" :page-sizes="pageSizes"
          :page-size="pageSize" :layout="paginationLayout" :total="pageCount">
        </el-pagination>
      </div>
    </div>

    <user-form :visible.sync="isShowModel" :title="title" :tree="treeData" :userType="editUserType" :parent-ids="parentIds" :member-id="editMemberId" @update="getPageDataList()"></user-form>

    <depart-change :visible.sync="isShowChangeModel" :depart="treeData" ref="DepartChangeRef" @update="getPageDataList()"></depart-change>

    <power-form :visible.sync="isShowPowerModel" :item-id="editMemberId" :name="title" :userType="editUserType" @update="getPageDataList()"></power-form>
  </div>
</template>

<script>
import Setting from '@/settings';
import { mapGetters } from 'vuex';
import { GetDepartmentMemberList, RemoveUser, UpdateUserStatus } from '@/views/user-management/services/index';
import UserForm from '@/views/user-management/components/userForm';
import PowerForm from '@/views/user-management/components/powerForm';
import DepartChange from '@/views/user-management/components/departChange';

export default {
  components: {
    UserForm,
    PowerForm,
    DepartChange
  },
  props: {
    currentNode: {
      type: Object,
      default: null
    },
    treeData: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      title: '',
      queryForm: {
        search: '',
        status: '',
      },
      pageIndex: 1,
      pageSize: Setting.defaultTablePaginationSize,
      pageSizes: Setting.tablePaginationSizes,
      tableHeaderStyle: Setting.tableHeaderStyle,
      paginationLayout: Setting.tablePaginationLayout,
      pageData: [],
      pageCount: 0,
      loading: false,
      isShowModel: false,
      isShowPowerModel: false,
      isShowChangeModel: false,
      multipleSelection: [],
      statusDataList: [
        { value: '', label: '全部' },
        { value: '0', label: '启用' },
        { value: '1', label: '禁用' },
      ],
      editMemberId: null,
      editUserType: 0,
      parentIds: []
    }
  },
  watch: {
    currentNode: {
      immediate: true,
      handler: function (newValue) {
        if (!newValue) return;
        this.getPageDataList();
      }
    }
  },
  computed: {
    ...mapGetters(['roleBtns'])
  },
  methods: {
    configOption(rowData) {
      this.title = rowData.name;
      this.editUserType = rowData.type;
      this.editMemberId = rowData.id;
      this.isShowPowerModel = true;
    },
    memberRemoveOption() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$message.warning('请选择需要删除的用户!');
        return;
      }
      this.removeDepartChildOption(this.multipleSelection.map(item => item.id));
    },
    removeDepartChildOption(nodeIds) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            RemoveUser({ userIds: nodeIds })
              .then(data => {
                instance.confirmButtonLoading = false;
                if (data.code == 200) {
                  this.$message.success('删除成功!');
                  done()
                } else {
                  this.$message.success('删除失败!');
                }
              })
              .catch(error => {
                instance.confirmButtonLoading = false;
              })
          } else {
            done();
          }
        }
      }).then(() => {
        this.getPageDataList();
      })
    },
    changeStatus(event, rowData) {
      this.loading = true;
      UpdateUserStatus({ id: rowData.id })
        .finally(() => (this.loading = false))
        .then(data => {
          if (data.code == 200) {
            this.$message.success(event ? '启用成功!' : '禁用成功!');
            rowData.checkStatus = event ? 0 : 1;
          } else {
            this.$message.error(event ? '启用失败!' : '禁用失败!');
          }
        })
        .catch(error => {
          this.$message.error(error);
        })
    },
    memberChangeOption() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$message.warning('请选择需要调整部门的用户!');
        return;
      }
      this.isShowChangeModel = true;
      this.$refs.DepartChangeRef.idLists = this.multipleSelection.map(item => item.id);
    },
    addMemberOption() {
      this.parentIds = this.$parent.deepTreeData(this.currentNode.id, this.treeData).map(item => item.id);
      this.editMemberId = null;
      this.editUserType = 0;
      this.title = '添加成员';
      this.isShowModel = true;
    },
    editMemberOption(rowData) {
      this.parentIds = [];
      this.editMemberId = rowData.id;
      this.editUserType = rowData.type;
      this.title = '编辑成员';
      this.isShowModel = true;
    },
    handleSelectionChange(selectlist) {
      this.multipleSelection = selectlist;
    },
    handlePagingChange(event) {
      this.pageIndex = event;
      this.getPageDataList();
    },
    handleSizeChange(event) {
      this.pageIndex = 1;
      this.pageSize = event;
      this.getPageDataList();
    },
    getPageDataList() {
      this.loading = true;
      GetDepartmentMemberList({
        proId: 4,
        depId: this.currentNode.id,
        search: this.queryForm.search,
        checkStatus: this.queryForm.status,
        pageNum: this.pageIndex,
        pageSize: this.pageSize
      })
        .finally(() => (this.loading = false))
        .then(data => {
          if (data.code == 200) {
            this.pageData = (data.data.list && data.data.list.length) ? data.data.list.map(item => {
              if (item.userType == 3) {
                if (item.isMch == 1 && item.isStore == 0) {
                  item.type = 1;
                } else if (item.isMch == 0 && item.isStore == 1) {
                  item.type = 2;
                } else if (item.isMch == 1 && item.isStore == 1) {
                  item.type = 3;
                }
              } else {
                item.type = item.userType;
              }
              return item;
            }) : [];
            this.pageCount = data.data.total;

            if ((!data.data.list || !data.data.list.length) && this.pageIndex > 1) {
              this.pageIndex = 1;
              this.getPageDataList();
            }
          }
        })
    },
    resetOption() {
      this.queryForm.search = '';
      this.queryForm.status = '';
      this.getPageDataList();
    }
  }
}
</script>

<style lang="scss" scoped>
.width_104 {
  width: 104px;
}
</style>
